走 Angular Workspace 開發的話,並非設定在根目錄,而是在各專案 projects 裡新增專屬於環境變數的資料夾。
檔案結構看起來如下:
projects/
├── app/
│ └── src/
│ └── environments/
│ ├── environment.ts # 開發預設 (Local)
│ ├── environment.develop.ts # 開發環境
│ └── environment.prod.ts # 正式環境
├── pc/
│ └── src/
│ └── environments/
│ ├── environment.ts
│ └── environment.develop.ts
Angular 官方有提供 生成環境指令 :
$ ng generate environments[options]
在 options 處改為專案名稱即可,例如以下:
$ ng generate environments --project=app
$ ng generate environments --project=pc
若有 API 金鑰,請進
.gitginore,只git push.env.example檔案。

environment.ts 檔案export const environment = {
production: false, // 正式環境為 true,目的是去壓縮 .js .ts .css .scss,最後的檔案會比較小,不過不容易 Debug。
apiUrl: 'http://my-prod-url' // API 伺服器路徑
name: 'local' // key 皆為自定義名稱
};
angular.config 設定檔若是使用指令ng generate environments新增環境變數,會自動幫妳寫好。
"configurations": {
"development": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.development.ts"
}
],
…
這邊的設定的意思是:
當你打包專案時 ng build --configuration development,src/environments/environment.ts 檔案將被替換為該檔案的特定於目標的版本 src/environments/environment.development.ts。
官網寫得很詳細,可以閱讀官方文件 來了解。
package.json npm 指令 "scripts": {
"build:p:dev": "ng build proposal --configuration develop",
"build:a:dev": "ng build application --configuration develop"
},
import { environment } from './../environments/environment';
this.http.get(environment.apiUrl).subscribe();
透過以上的步驟,在不改動到商業邏輯前提下可以輕鬆建立不同的環境囉!
參考資料: